#!/usr/bin/perl

#
# Validate a registration; put all the fields in as hidden
# fields, and show the result of doing "validate" on them.
# At the moment, focus on the Persons form.
#
use strict;
use vars qw($CPUTRACE $sofar $counterroot $users $persons $validator);
use vars qw($clean);
use CGI;
use CGI::Carp;
BEGIN {
    $CPUTRACE = 0;

    $sofar = (times())[0];
    $CPUTRACE && warn "In early compile, $sofar seconds of CPU was already used\n";
}
use Fcntl;

use Counter;
use Validate::Persons;
use Validate::Places;
use IsEmail;
use ErrorForm;
use CounterCGI;

$sofar = (times())[0];
$CPUTRACE && warn "At startup, $sofar seconds of CPU was already used\n";
$counterroot = $ENV{COUNTER_ROOT}?$ENV{COUNTER_ROOT}:"/home/counter";
chdir($counterroot) 
    || die "Unable to chdir to $counterroot";

$users = Counter::open();
$persons = Counter::openfile("persons");
$validator = new Validate::Persons;

eval { doit() };
warn "Result of doit: $@\n";


    $sofar = (times())[0];
$CPUTRACE && warn "At exit, $sofar seconds of CPU was used\n";


sub doit {

# Get the input
my $q = new CGI;
my %entry;
for my $name ($q->param()) {
    my $value = join(", ", $q->param($name));
    if ($value =~ /[\000-\037]/) {
	&errorForm("bogon value");
    }
    # Use commas for multi-choice fields
    if ($entry{$name}) {
	$entry{$name} .= ", ";
	$entry{$name} .= $value;
    } else {
	$entry{$name} = $value;
    }
    $entry{$name} =~ s/\s+$//; # strip trailing spaces
}
# special mr. fixit stuff
if ($entry{"started-year"} && $entry{"started-month"}) {
    $entry{"started"} = $entry{"started-month"} . " " . $entry{"started-year"};
    delete $entry{"started-year"};
    delete $entry{"started-month"};
}
# Check for some obvious bogons
$entry{"sendreplyto"} =~ s/^ +//; # leading blanks sometimes occur
if ($entry{"sendreplyto"} !~ /\S+@\S+/) {
    &errorForm("no email");
} elsif (!IsEmail::isemail($entry{"sendreplyto"}, "nosmtp")) {
    &errorForm("illegal email", $entry{"sendreplyto"}, $IsEmail::notemailbecause);
}

# Check if he's attempting to take someone else's email
if ($users->getbyemail($entry{sendreplyto})) {
    &errorForm("duplicate email", $entry{sendreplyto});
}

# Fill in the email if not filled in (the form says to type
# SECRET if you don't want it revealed)
if (!$entry{email}) {
    $entry{email} = $entry{sendreplyto};
}

print <<EoF;
Content-type: text/html; charset="utf-8"

<html><head>
EoF

CounterCGI::pagehead("Person registration review", "head");
print "</head>\n<BODY bgcolor=\"white\">\n";
CounterCGI::pagetop($q);

print <<EoF;
<h1><img src="/gifs/Logo-small.png" alt="Linux Counter Logo">
Person registration - review</h1>
The table below shows what you entered, and, if relevant, what the
counter will summarize what you entered as.
<p>
If you like what you see, press the "I accept!" button below. If you don't, use
the "back" button in your browser to go back and modify it.
<p>
Note that this is the internal counter representation; it's been
chosen for utility, not beauty!
<p>
<FORM METHOD=POST action="/perl/person-counter.pl">
<table border>
<tr><th>Field<th>You entered<th>Interpreted as
EoF

# Find the place, if possible
my @placenames = Validate::Places::prettynames(\%entry);

for my $field ("sendreplyto", $persons->fields) {
    $entry{$field} = '' if !defined($entry{$field}); # avoid warnings
   print "<input type=hidden name=\"$field\" value=\"$entry{$field}\">\n";
   if ($field eq "country") {
       $clean = $placenames[0];
   } elsif ($field eq "state") {
       $clean = $placenames[1];
       if (!$clean && $entry{state}) {
	   $clean = "(ignored)";
       }
   } elsif ($field eq "city" && $placenames[2]) {
       $clean = $placenames[2];
   } else {
       $clean = $validator->cleanfield($field, $entry{$field});
   }
   # lazy avoidance of perl warnings....
   $clean = "" if !defined($clean);
   $entry{$field} = "" if !defined($entry{$field});
   if ($clean eq "" && $entry{$field} eq "") {
      $clean = "&nbsp;"; # Mark as "empty"
      $entry{$field} = "&nbsp;";
   } elsif ($clean eq $entry{$field}) { # No change - no comment
      $clean = "";
   } elsif ($clean eq "") {
      $clean = "<b>Bogus value</b>";
   }
   if (($field eq "sendreplyto") || ($field eq "email")) {
       printf "<tr><td>%s<td>%s<td>%s\n", $field, CounterCGI::emailCloaking($entry{$field},0), $clean;
   } else {
       printf "<tr><td>%s<td>%s<td>%s\n", $field, $entry{$field}, $clean;
   }
   delete $entry{$field};
}
print "</table>\n";
if (keys(%entry)) {
   print "The following extra fields were in your entry:<p>\n"; 
   for my $field (keys(%entry)) {
      print "$field: $entry{$field}<br>\n";
   }
}

print <<EoF;
<p>
<inPUT TYPE="submit" VALUE="I accept!">
</form>
EoF

CounterCGI::pagebottom();
print "\n</body>\n</html>";

}



